from traceback import print_tb, print_list

from django.contrib.gis.geometry import json_regex
from django.db.models import Count
from django.shortcuts import render
import re
from app01.models import HouseInfo, HouseFeature
from app01.models import UserInfo
from app01.models import Province

from django.http import HttpResponse, JsonResponse


# Create your views here.


class CityAvgPrice:
    city = ""
    avg_price = 0

    def __init__(self, name, avg_price):
        self.name = name
        self.avg_price = avg_price


# 获取所有省份
def get_province(info):
    cities = HouseInfo.objects.values('city').annotate(count=Count('city'))
    return cities

def test(request):
    name = "韩超"
    roles = ["管理员", "CEO", "保安"]
    user_info = {"name": "嘿嘿", "age": 15, "phone": "110"}

    user_list = [
        {"name": "嘿嘿", "age": 15, "phone": "110"},
        {"name": "哈哈", "age": 25, "phone": "120"},
        {"name": "呵呵", "age": 35, "phone": "119"},
    ]
    return render(request, 'test.html', {"n1": name, "n2": roles, "n3": user_info, "n4": user_list})


def getpost(request):
    # 获取请求方式
    print(request.method)
    # 在URL上传递值
    print(request.GET)
    # 在请求体中提交数据
    print(request.POST)

    # return redirect("https://www.baidu.com")
    return render(request, 'getpost.html')


def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username, password)
        if username == "123" and password == "123":
            # return render(request, 'login.html')
            return render(request, 'test.html')
        return render(request, 'login.html', {"err_message": "登录失败"})


def orm(request):
    # 新增
    # models.UserInfo.objects.create(name="root",passwd="xsaxl",age=25)
    # 删除
    UserInfo.objects.filter(id=3).delete()
    # 删除所有
    # UserInfo.objects.all().delete()
    # 查询
    datalist = UserInfo.objects.all()

    # 更新
    UserInfo.objects.update(passwd=123)
    UserInfo.objects.filter(id=2).update(passwd="xsaxl")

    return render(request, "orm.html")


def info_list(request):
    allUserInfo = UserInfo.objects.all()
    print(allUserInfo)

    return render(request, "info_list.html", {"user_list": allUserInfo})


def index(request):
    return render(request, "index.html",{"province":"山东"})

def sdfy(request):
    province = request.GET.get("province")
    # 去除字符串末尾的省字
    province = re.sub("省$","",province)

    province_objlist = Province.objects.filter(provinces=province)
    city_list = []
    for item in province_objlist:
        city_list.append(item.city)
        # print(item.city)

    city_number = []
    region_in_city_list = {}
    for item in city_list:
        city_number.append(HouseInfo.objects.filter(city=item).count())
        # 获取该城市的所有地区
        region_query = HouseInfo.objects.filter(city=item)
        region_list = []
        for i in region_query:
            region_name = i.area.split()[0]
            if region_name not in region_list:
                region_list.append(region_name)
        region_in_city_list[item] = region_list


    city_dict = dict(zip(city_list,city_number))

    return render(request, "sdfy.html",{"province":province+"省","city_dict":city_dict,"region_in_city_list":region_in_city_list})


def chart2(request):
    return render(request, "chart2.html")


def chart4(request):
    return render(request, "chart4.html")


def chart3(request):
    return render(request, "chart3.html")


def chart5(request):
    return render(request, "chart5.html")

# 获取山东省各市的房源平均价
def get_city_avg(request):
    # 获取所有的house_info信息
    house_list = HouseInfo.objects.all()
    # 获取所有山东省份
    cityes_count = get_province(HouseInfo)

    city_list = []
    avg = {}
    # 转换为城市-数量字典
    city_cnt = {}

    for item in cityes_count:
        city_list.append(item["city"])
        avg[item["city"]] = 0
        city_cnt[item["city"]] = item["count"]

    for item in house_list:
        match = item.ave_price.strip("元/平米")
        # print(item.city, match)
        avg[item.city] += int(match)

    for k, v in avg.items():
        avg[k] = int(v / city_cnt[k])

    # print("城市列表", city_list)
    # print("城市数量字典", city_cnt)
    # print("平均房价字典", avg)

    city_avg = []
    for item in city_list:
        city_avg.append(avg[item])

    # print(city_avg)

    result = {
        "status":True,
        "data":{
            "city_list":city_list,
            "avg":avg
        }
    }
    return JsonResponse(result)


# 山东省各城市房源信息页面 左侧城市列表获取和该城市的所有区
#
def guaipai(request):

    # 获取所有日期，年-月-日
    allyears = HouseInfo.objects.values('times')
    # 年-数量
    year_cnt = {}
    for item in allyears:
        # 获取日期字符串中的年份
        dd = item["times"]
        year = dd.split("-")[0]
        year_cnt[year] = year_cnt.get(year,0)+1

    year_list = []
    cnt_list = []
    for k,v in year_cnt.items():
        year_list.append(k)
        cnt_list.append(v)

    print(year_list,cnt_list)

    result = {
        "status": True,
        "data": {
            "year_list": year_list,
            "cnt_list": cnt_list
        }
    }
    return JsonResponse(result)


def cityinfo_get(request):
    house_list = HouseInfo.objects.all()

    return house_list

def cityfy(request):
    province = request.GET.get("province")
    city = request.GET.get("city")
    region_dict = {}

    return render(request, "cityfy.html",{"province":province,"city":city,"region_dict":region_dict})


def shandong_info(request):
    # 获取所有的house_info信息
    house_list = HouseInfo.objects.all()
    # 获取所有山东省份
    cityes_count = get_province(HouseInfo)

    city_list = []
    avg = {}
    # 转换为城市-数量字典
    city_cnt = {}

    for item in cityes_count:
        city_list.append(item["city"])
        avg[item["city"]] = 0
        city_cnt[item["city"]] = item["count"]

    for item in house_list:
        match = item.ave_price.strip("元/平米")
        # print(item.city, match)
        avg[item.city] += int(match)

    for k, v in avg.items():
        avg[k] = int(v / city_cnt[k])

    city_avg = []
    for item in city_list:
        city_avg.append(avg[item])

    # print(city_avg)

    jsonData = []
    jsonData.append(["市", "房源总数", "均价"])
    for i in range(len(city_list)):
        jsonData.append([city_list[i]+"市", city_cnt[city_list[i]], city_avg[i]])

    result = {
        "status": True,
        "data": {
            "jsonData": jsonData,
        }
    }

    return JsonResponse(result)


def region_avg(request):
    city = request.GET.get("city")

    city_list = HouseInfo.objects.filter(city=city)
    region_list = []
    for item in city_list:
        # 获取第一个空格前的字符串
        region_name = item.area.split()[0]
        if  region_name not in region_list :
            region_list.append(region_name)

    jsonData = [["区", "房源总数", "均价"],]
    for item in region_list:
        cnt = 0
        price = 0.0
        for i in city_list:
            if i.area.split()[0] == item:
                cnt += 1
                price += float( '{:.2f}'.format( float(i.ave_price.strip("元/平米")) ) )
        jsonData.append([item, cnt,  float( '{:.2f}'.format(price/cnt) ) ])


    result = {
        "status": True,
        "data": {
            "jsonData": jsonData,
        }
    }

    return JsonResponse(result)


 # 获取市级地区的下属地区
def region_info(request):
    city_name = request.GET.get("city")

    house_list = HouseInfo.objects.filter(city=city_name)
    region_list = []
    for item in house_list:
        region_name = item.area.split()[0]
        if region_name not in region_list :
            region_list.append(region_name)

    result = {
        "status": True,
        "data": {
            "region_list": region_list,
        }
    }

    return JsonResponse(result)



def house_detail(request):
    province = request.GET.get("province")
    city = request.GET.get("city")
    region = request.GET.get("region")
    zhuangxiu = request.GET.get("zhuangxiu")
    huxing = request.GET.get("huxing")
    louceng = request.GET.get("louceng")
    chanquan = request.GET.get("chanquan")
    diya = request.GET.get("diya")
    mianji = request.GET.get("mianji")
    fangjia = request.GET.get("fangjia")
    # 获取省份、城市下的所有
    house_list =  HouseInfo.objects.filter(city=city,area__contains=region)
    # 装修
    if zhuangxiu == "1" :
        house_list = house_list.filter(decoration__contains ="简装")
    elif zhuangxiu == "2" :
        house_list = house_list.filter(decoration__contains ="精装")
    elif zhuangxiu == "3" :
        house_list = house_list.filter(decoration__contains="其他")
    # 户型
    if huxing == "1" :
        house_list = house_list.filter(decoration__contains ="平层")
    elif huxing == "2" :
        house_list = house_list.filter(decoration__contains ="复式")
    elif huxing == "3" :
        house_list = house_list.filter(decoration__contains="毛坯")
    # 楼层
    if louceng == "1" :
        house_list = house_list.filter(floor__contains ="高楼层")
    elif louceng == "2" :
        house_list = house_list.filter(floor__contains ="中楼层")
    elif louceng == "3" :
        house_list = house_list.filter(floor__contains="低楼层")
    # 产权
    if chanquan == "1" :
        house_list = house_list.filter(property_right__contains ="公有")
    elif chanquan == "2" :
        house_list = house_list.filter(property_right__contains ="非公有")

    # 抵押
    if diya == "1" :
        house_list = house_list.filter(di_ya__contains ="有抵押")
    elif diya == "2" :
        house_list = house_list.filter(di_ya__contains ="无抵押")

    def is_include(min,max,cur):
        if cur >= min and cur <= max :
            return True
        else:
            return False

    # 面积
    if mianji == "1" :
        # 0-50
        new_house = []
        for item in house_list:
            manji = float(item.building_area.strip("平米"))
            if is_include(0, 50, manji):
                new_house.append(item)
        house_list = new_house
    elif mianji == "2" :
        # 50-100
        new_house = []
        for item in house_list:
            manji = float(item.building_area.strip("平米"))
            if is_include(50, 100, manji):
                new_house.append(item)
        house_list = new_house
    elif mianji == "3" :
        # 100-200
        new_house = []
        for item in house_list:
            manji = float(item.building_area.strip("平米"))
            if is_include(100, 200, manji):
                new_house.append(item)
        house_list = new_house
    elif mianji == "4" :
        # 200-
        new_house = []
        for item in house_list:
            manji = float(item.building_area.strip("平米"))
            if is_include(200, 10000, manji):
                new_house.append(item)
        house_list = new_house

    # 房价
    if fangjia == "1" :
        # 0-10
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(0, 10, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "2" :
        # 10-20
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(10, 20, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "3" :
        # 20-50
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(20, 50, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "4" :
        # 50-100
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(50, 100, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "5" :
        # 100-200
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(100, 200, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "6" :
        # 200-500
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(200, 500, totl):
                new_house.append(item)
        house_list = new_house
    elif fangjia == "7" :
        # 500
        new_house = []
        for item in house_list:
            totl = float(item.t_price)
            if is_include(5, 1000000000, totl):
                new_house.append(item)
        house_list = new_house

    #     转换为json
    jsonData = []
    index_list = []
    for item in house_list:
        jsonData.append([item.neighborhood_name, # 0
                         item.area,# 1
                         item.building_type,# 2
                         item.decoration,# 3
                         item.house_type,# 4
                         item.orientation,# 5
                         item.floor,# 6
                         item.property_right,# 7
                         item.di_ya,# 8
                         item.building_area,# 9
                         item.ave_price,# 10
                         item.t_price,# 11
                         item.times,# 12
                         item.city, # 13
                         item.id, # 14
        ])
        index_list.append(item.id)

    for item in jsonData:
        print(item)

    maxFenye = len(jsonData) / 10.0
    if maxFenye - int(maxFenye) > 0:
        maxFenye = int(maxFenye) + 1

    # jsonData = jsonData[0:10];


    # 0 小区名称           1 所在区域 2 户型结构       3  装修情况     4 房屋户型      5房屋朝向      6所在楼层   7产权             8 抵押  9 建筑面积         10 房价        11 总价     12 挂牌时间
    #   neighborhood_name   area     building_type   decoration    house_type   orientation  floor      property_right    diya    building_area      avg_price  t_price  times

    result = {
        "status": True,
        "data": {
            "jsonData" : jsonData,
            "maxFenye" :  maxFenye,
            "index_list" : index_list
        }
    }

    return JsonResponse(result)


def house_feature(request):
    id =  request.GET.get("id")

    feat = HouseFeature.objects.filter(id=id)[0]
    ret = [feat.mai_dian,feat.jie_shao,feat.hu_xing]
    result = {
        "status": True,
        "data": {
            "ret": ret
        }
    }

    return JsonResponse(result)


def chart1(request):
    return render(request, "chart1.html")